# spine-leaf-backend/app.py
from flask import Flask, jsonify
from flask_cors import CORS
import random
import time
import threading
from prometheus_client import CollectorRegistry, Gauge

app = Flask(__name__)
CORS(app)

# 模拟Prometheus指标
registry = CollectorRegistry()
spine_cpu = Gauge('spine_cpu_usage', 'CPU usage of spine switches', ['device'], registry=registry)
spine_memory = Gauge('spine_memory_usage', 'Memory usage of spine switches', ['device'], registry=registry)
leaf_cpu = Gauge('leaf_cpu_usage', 'CPU usage of leaf switches', ['device'], registry=registry)
leaf_memory = Gauge('leaf_memory_usage', 'Memory usage of leaf switches', ['device'], registry=registry)
server_cpu = Gauge('server_cpu_usage', 'CPU usage of servers', ['device'], registry=registry)
server_memory = Gauge('server_memory_usage', 'Memory usage of servers', ['device'], registry=registry)
link_traffic = Gauge('link_traffic', 'Traffic on network links', ['source', 'target'], registry=registry)

# 设备列表
spines = ['spine-01', 'spine-02']
leaves = ['leaf-01', 'leaf-02', 'leaf-03', 'leaf-04']
servers = ['server-01', 'server-02', 'server-03', 'server-04']


# 模拟数据更新线程
def update_metrics():
    while True:
        # 更新Spine交换机指标
        for spine in spines:
            spine_cpu.labels(device=spine).set(random.randint(10, 60))
            spine_memory.labels(device=spine).set(random.randint(20, 80))

        # 更新Leaf交换机指标
        for leaf in leaves:
            leaf_cpu.labels(device=leaf).set(random.randint(15, 70))
            leaf_memory.labels(device=leaf).set(random.randint(25, 85))

        # 更新服务器指标
        for server in servers:
            server_cpu.labels(device=server).set(random.randint(5, 90))
            server_memory.labels(device=server).set(random.randint(10, 95))

        # 更新链路流量
        for spine in spines:
            for leaf in leaves:
                link_traffic.labels(source=spine, target=leaf).set(random.randint(100, 1000))

        for i, leaf in enumerate(leaves):
            server_index = i * 2
            if server_index < len(servers):
                link_traffic.labels(source=leaf, target=servers[server_index]).set(random.randint(50, 500))
            if server_index + 1 < len(servers):
                link_traffic.labels(source=leaf, target=servers[server_index + 1]).set(random.randint(50, 500))

        time.sleep(5)


# 启动后台线程更新指标
thread = threading.Thread(target=update_metrics)
thread.daemon = True
thread.start()


@app.route('/api/metrics')
def get_metrics():
    """获取所有监控指标"""
    metrics = {
        'spines': {},
        'leaves': {},
        'servers': {},
        'links': []
    }

    # 获取Spine交换机指标
    for spine in spines:
        metrics['spines'][spine] = {
            'cpu': spine_cpu.labels(device=spine)._value.get(),
            'memory': spine_memory.labels(device=spine)._value.get()
        }

    # 获取Leaf交换机指标
    for leaf in leaves:
        metrics['leaves'][leaf] = {
            'cpu': leaf_cpu.labels(device=leaf)._value.get(),
            'memory': leaf_memory.labels(device=leaf)._value.get()
        }

    # 获取服务器指标
    for server in servers:
        metrics['servers'][server] = {
            'cpu': server_cpu.labels(device=server)._value.get(),
            'memory': server_memory.labels(device=server)._value.get()
        }

    # 获取链路流量
    for spine in spines:
        for leaf in leaves:
            metrics['links'].append({
                'source': spine,
                'target': leaf,
                'traffic': link_traffic.labels(source=spine, target=leaf)._value.get()
            })

    for i, leaf in enumerate(leaves):
        server_index = i * 2
        if server_index < len(servers):
            metrics['links'].append({
                'source': leaf,
                'target': servers[server_index],
                'traffic': link_traffic.labels(source=leaf, target=servers[server_index])._value.get()
            })
        if server_index + 1 < len(servers):
            metrics['links'].append({
                'source': leaf,
                'target': servers[server_index + 1],
                'traffic': link_traffic.labels(source=leaf, target=servers[server_index + 1])._value.get()
            })

    return jsonify(metrics)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)